define(function (require, exports, module) {
    /**
     * 通用js方法封装处理
     */
    // 日期格式化
    function parseTime(time, pattern) {
        if (arguments.length === 0 || !time) {
            return null
        }
        const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
        let date
        if (typeof time === 'object') {
            date = time
        } else {
            if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
                time = parseInt(time)
            } else if (typeof time === 'string') {
                time = time.replace(new RegExp(/-/gm), '/');
            }
            if ((typeof time === 'number') && (time.toString().length === 10)) {
                time = time * 1000
            }
            date = new Date(time)
        }
        const formatObj = {
            y: date.getFullYear(),
            m: date.getMonth() + 1,
            d: date.getDate(),
            h: date.getHours(),
            i: date.getMinutes(),
            s: date.getSeconds(),
            a: date.getDay()
        }
        const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
            let value = formatObj[key]
            // Note: getDay() returns 0 on Sunday
            if (key === 'a') {
                return ['日', '一', '二', '三', '四', '五', '六'][value]
            }
            if (result.length > 0 && value < 10) {
                value = '0' + value
            }
            return value || 0
        })
        return time_str
    }

    // 表单重置
    function resetForm(refName) {
        if (this.$refs[refName]) {
            this.$refs[refName].resetFields();
        }
    }

   // 添加日期范围
   function addDateRange(params, dateRange) {
   	var search = params;
   	search.beginTime = "";
   	search.endTime = "";
   	if (null != dateRange && '' != dateRange) {
   		search.beginTime = this.dateRange[0];
   		search.endTime = this.dateRange[1];
   	}
   	return search;
   }

    // 回显数据字典
    function selectDictLabel(datas, value) {
        var actions = [];
        Object.keys(datas).some((key) => {
            if (datas[key].dictValue == ('' + value)) {
                actions.push(datas[key].dictLabel);
                return true;
            }
        })
        return actions.join('');
    }

    // 回显数据字典（字符串数组）
    function selectDictLabels(datas, value, separator) {
        var actions = [];
        var currentSeparator = undefined === separator ? "," : separator;
        var temp = value.split(currentSeparator);
        Object.keys(value.split(currentSeparator)).some((val) => {
            Object.keys(datas).some((key) => {
                if (datas[key].dictValue == ('' + temp[val])) {
                    actions.push(datas[key].dictLabel + currentSeparator);
                }
            })
        })
        return actions.join('').substring(0, actions.join('').length - 1);
    }

    // 字符串格式化(%s )
    function sprintf(str) {
        var args = arguments, flag = true, i = 1;
        str = str.replace(/%s/g, function () {
            var arg = args[i++];
            if (typeof arg === 'undefined') {
                flag = false;
                return '';
            }
            return arg;
        });
        return flag ? str : '';
    }

    /**
     * 构造树型结构数据
     * @param {*} data 数据源
     * @param {*} id id字段 默认 'id'
     * @param {*} parentId 父节点字段 默认 'parentId'
     * @param {*} children 孩子节点字段 默认 'children'
     * @param {*} rootId 根Id 默认 0
     */
    function handleTree(data, id, parentId, children, rootId) {
        id = id || 'id'
        parentId = parentId || 'parentId'
        children = children || 'children'
        rootId = rootId || Math.min.apply(Math, data.map(item => {
            return item[parentId]
        })) || 0
        //对源数据深度克隆
        const cloneData = JSON.parse(JSON.stringify(data))
        //循环所有项
        const treeData = cloneData.filter(father => {
            let branchArr = cloneData.filter(child => {
                //返回每一项的子级数组
                return father[id] == child[parentId]
            });
            branchArr.length > 0 ? father.children = branchArr : delete father.children;
            //返回第一层
            return father[parentId] == rootId;
        });
        return treeData != '' ? treeData : data;
    }

    // 全局方法挂载
    Vue.prototype.parseTime = parseTime
    Vue.prototype.resetForm = resetForm
    Vue.prototype.addDateRange = addDateRange
    Vue.prototype.selectDictLabel = selectDictLabel
    Vue.prototype.selectDictLabels = selectDictLabels
    Vue.prototype.handleTree = handleTree
	
	
	let downloadLoadingInstance;
	//oss独有下载方法
	Vue.prototype.downloadOss = function(ossId,fileName){
		var url = alluse.bigcenter + '/system/oss/download/' + ossId;
		    downloadLoadingInstance = window.ELEMENT.Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
		var finalUrl = alluse.bigcenter + '/system/oss/download/' + ossId;
		const errorCode = {
		    '401': '认证失败，无法访问系统资源',
		    '403': '当前操作没有权限',
		    '404': '访问资源不存在',
		    'default': '系统未知错误，请反馈给管理员'
		}
		var request = new XMLHttpRequest();
		var that = this
		// request.onreadystatechange = async function() {
		request.onreadystatechange =  function() {
			if (request.readyState === 1) {
				request.setRequestHeader("Authorization", $.cookie(common.getTokenKey()));
				request.setRequestHeader("Content-Type","application/json;charset=UTF-8")
			} else if(request.readyState === 4) {
		        if(request.status === 200) {
		            const data = request.response
		            // const isLogin = await blobValidate(data);
		            const isLogin =  blobValidate(data);
		            if (isLogin) {
		                const blob = new Blob([data])
		                window.saveAs(blob, fileName);
		            } else {
		                // const resText = await data.text();
		                const resText =  data.text();
		                const rspObj = JSON.parse(resText);
		                const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
		                that.$message({showClose: true, message: errMsg, type: "error"});
		            }
		            downloadLoadingInstance.close();
		        } else {
		            console.log(request.responseText)
		            that.$message({showClose: true, message: '下载文件出现错误，请联系管理员！', type: "error"});
		            downloadLoadingInstance.close();
		        }
		    } else if(request.readyState === 2) {
		        if(request.status === 200) {
		            request.responseType = "blob";
		        } else {
		            request.responseType = "text";
		        }
		    }
		};
		request.open("GET", finalUrl, true);
		request.send();
		
		// 验证是否为blob格式
		// const blobValidate = async function blobValidate(data) {
		const blobValidate =  function blobValidate(data) {
		    try {
		        // const text = await data.text();
		        const text =  data.text();
		        JSON.parse(text);
		        return false;
		    } catch (error) {
		        return true;
		    }
		}	
	}

    
    Vue.prototype.download = function download(filename,str) {
        downloadLoadingInstance = window.ELEMENT.Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
		var finalUrl = "";
		if(!str){
			finalUrl = alluse.bigcenter + "/common/download?fileName=" + encodeURI(filename) + "&delete=" + true
		}else{
			finalUrl = alluse.bigcenter + str;
		}

        // 不交互，直接进行下载
        // window.location.href = finalUrl

        const errorCode = {
            '401': '认证失败，无法访问系统资源',
            '403': '当前操作没有权限',
            '404': '访问资源不存在',
            'default': '系统未知错误，请反馈给管理员'
        }
        var request = new XMLHttpRequest();
        var that = this
        // request.onreadystatechange = async function() {
        request.onreadystatechange =  function() {
            if(request.readyState === 4) {
                if(request.status === 200) {
                    const data = request.response
                    // const isLogin = await blobValidate(data);
                    const isLogin =  blobValidate(data);
                    if (isLogin) {
                        const blob = new Blob([data])
                        window.saveAs(blob, filename)
                    } else {
                        // const resText = await data.text();
                        const resText =  data.text();
                        const rspObj = JSON.parse(resText);
                        const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
                        that.$message({showClose: true, message: errMsg, type: "error"});
                    }
                    downloadLoadingInstance.close();
                } else {
                    console.log(request.responseText)
                    that.$message({showClose: true, message: '下载文件出现错误，请联系管理员！', type: "error"});
                    downloadLoadingInstance.close();
                }
            } else if(request.readyState === 2) {
                if(request.status === 200) {
                    request.responseType = "blob";
                } else {
                    request.responseType = "text";
                }
            }
        };
        request.open("GET", finalUrl, true);
        request.send();

        // 验证是否为blob格式
        const blobValidate =  function blobValidate(data) {
        // const blobValidate = async function blobValidate(data) {
            try {
                // const text = await data.text();
                const text =  data.text();
                JSON.parse(text);
                return false;
            } catch (error) {
                return true;
            }
        }
    }
	Vue.prototype.doLoading = function() {
		return this.$loading({
			lock: true,
			text: '加载中..',
			spinner: 'el-icon-loading',
			background: 'rgba(0, 0, 0, 0.7)'
		})
	}

    Vue.prototype.msgSuccess = function (msg) {
		this.$notify({
		  title: '成功',
		  duration:1500,
		  message: msg,
		  type: 'success'
		});
        // this.$message({showClose: true, message: msg, type: "success"});
    }

    Vue.prototype.msgError = function (msg) {
		this.$notify.error({
		          title: '错误',
				  duration:3000,
		          message: msg
		        });
        // this.$message({showClose: true, message: msg, type: "error"});
    } 
	Vue.prototype.msgWarning = function (msg) {
		this.$notify.warning({
		          title: '警告',
				  duration:3000,
		          message: msg
		        });
        // this.$message({showClose: true, message: msg, type: "error"});
    }
	Vue.prototype.msgInfo = function (msg) {
		this.$notify.info({
		          title: '消息',
				  duration:3000,
		          message: msg
		});
	    // this.$message({showClose: true, message: msg, type: "error"});
	}

    Vue.prototype.msgInfo = function (msg) {
        this.$message({showClose: true, message: msg, type: "info"});
    }
    Vue.prototype.getDicts = function (msg, callback) {
        $.get(alluse.bigcenter + "/system/dict/data/type/" + msg,
            (response) => {
                if (response.code === 200) {
                    callback(response)
                }
            });
    }
    Vue.prototype.getUserProfile = function (callback) {
        $.get(alluse.bigcenter + "/system/user/profile",
            (response) => {
                if (response.code === 200) {
                    callback(response)
                }
            });
    }
    Vue.prototype.selectAddress = function (callback) {
        $.get(alluse.bigcenter + "/system/address/select",
            (response) => {
                if (response.code === 200) {
                    callback(response)
                }
            });
    }

	Vue.prototype.uuid = function() {
			let d = new Date().getTime()
			if (window.performance && typeof window.performance.now === 'function') {
				d += performance.now() // use high-precision timer if available
			}
			const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
				const r = (d + Math.random() * 16) % 16 | 0
				d = Math.floor(d / 16)
				return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
			})
			return uuid.replace(new RegExp('-', 'g'), '')
		}

    // 权限指令
    Vue.directive('permission', {
        inserted(el, binding) {
            const {value} = binding
            const all_permission = '*:*:*'
            const permissions = window.config ? window.config.user.permissions : window.parent.config.user.permissions

            if (value && value instanceof Array && value.length > 0) {
                const permissionFlag = value

                const hasPermissions = permissions.some(permission => {
                    return all_permission === permission || permissionFlag.includes(permission)
                })

                if (!hasPermissions) {
                    el.parentNode && el.parentNode.removeChild(el)
                }
            } else {
                throw new Error(`请设置操作权限标签值`)
            }
        }
    })

    // 指定element ui的默认大小和层级
    Vue.prototype.$ELEMENT = { size: 'medium', zIndex: 19992016 };

    // 全局组件
    // 树选择
    Vue.component('treeselect', VueTreeselect.Treeselect)
    // 图片剪切
    Vue.use(window['vue-cropper'].default)
    // 分页
    Vue.component('pagination', require("./components/Pagination/Widget").onload())
    // svg图标
    Vue.component('svg-icon', require("./components/SvgIcon/Widget").onload())
    // 富文本编辑器
    Vue.component('editor', require("./components/Editor/Widget").onload())
    // 空
    Vue.component('empty', require("./components/Empty/Widget").onload())
	//图片预览
	Vue.component('oss-upload', require("./components/OssUpload/Widget").onload())
	//搜索显示隐藏
	Vue.component('RightToolbar', require("./components/RightToolbar/Widget").onload())
     // require("../../pc/lib/vue-components/index").onload()
})

